package com.yima.baseproj.utils;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import org.json.simple.JSONObject;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringToJsonConverter {
    public static String convertToJson(String input) {
        Pattern pattern = Pattern.compile("(\\w+)=([\\w\\u4e00-\\u9fa5]+)");
        Matcher matcher = pattern.matcher(input);
        JSONObject jsonObject = new JSONObject();
        while (matcher.find()) {
            jsonObject.put(matcher.group(1), matcher.group(2));
        }
        return jsonObject.toString(); // 返回JSON字符串表示，去掉空格
    }


    public static String convertToJsonTow(String input) {
        // 使用正则表达式匹配键值对
        Pattern pattern = Pattern.compile("(\\w+)=(\\w+(?:,\\w+)*)");
        Matcher matcher = pattern.matcher(input);
        // 创建JSON对象
        JSONObject jsonObject = new JSONObject();
        // 提取键值对并添加到JSON对象中
        while (matcher.find()) {
            String key = matcher.group(1);
            String values = matcher.group(2);
            String valueArray = Arrays.toString(values.split(","));
            String result = valueArray.replace(" ", ""); // 去除空格
            String s = extractContent(result);
            jsonObject.put(key, s);
        }

        // 返回JSON字符串表示
        return jsonObject.toJSONString();
    }

    private static String extractContent(String input) {
        Pattern pattern = Pattern.compile("\\[(.*?)\\]");
        Matcher matcher = pattern.matcher(input);
        if (matcher.find()) {
            return matcher.group(1);
        } else {
            return input;
        }
    }


    public static String extractContentImage(String data) {
        String[] keyValuePairs = data.split(", ");
        JSONObject jsonObject = new JSONObject();
        for (String pair : keyValuePairs) {
            String[] keyAndValue = pair.split("=", 2);
            jsonObject.put(keyAndValue[0].trim(), keyAndValue[1].trim());
        }
        return jsonObject.toJSONString();
    }

    public static Map<String, String> parseHashMap(Map<String, String[]> map) {
        Iterator<Map.Entry<String, String[]>> iterator = map.entrySet().iterator();
        Map<String, String> stringHashMap = new HashMap<>();
        map.entrySet().forEach(stringEntry -> {
            stringHashMap.put(stringEntry.getKey(), String.join(",", stringEntry.getValue()));
        });
        return stringHashMap;
    }
}
